<template>
  <div class="material-detail-container">
    <el-card v-if="material">
      <template #header>
        <div class="header-content">
          <span>物资详情</span>
          <el-button @click="$router.back()">返回</el-button>
        </div>
      </template>

      <div class="material-content">
        <h2>{{ material.name }}</h2>
        <div class="meta">
          <span>类别：{{ material.typeName }}</span>
          <span>当前库存：{{ material.quantity }}</span>
          <span>捐赠时间：{{ formatDate(material.createTime) }}</span>
        </div>
        <div class="description">
          <h3>物资描述</h3>
          <p>{{ material.description }}</p>
        </div>

        <div class="actions">
          <el-button
            type="primary"
            @click="handleRequest"
            :disabled="material.quantity <= 0"
          >
            申请物资
          </el-button>
          <el-button
            type="success"
            @click="handleDonate"
            style="margin-left: 10px"
          >
            捐赠物资
          </el-button>
        </div>
      </div>

      <div class="donation-history">
        <h3>申请记录</h3>
        <el-table :data="requestHistory" style="width: 100%">
          <el-table-column prop="username" label="申请人" />
          <el-table-column prop="phone" label="手机号" />
          <el-table-column prop="requestQuantity" label="申请数量" />
          <el-table-column prop="requestTime" label="申请时间">
            <template #default="{ row }">
              {{ formatDate(row.requestTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 申请对话框 -->
    <el-dialog
      v-model="requestDialogVisible"
      title="申请物资"
      width="500px"
    >
      <el-form
        ref="requestFormRef"
        :model="requestForm"
        :rules="requestRules"
        label-width="100px"
      >
        <el-form-item label="申请数量" prop="request_quantity">
          <el-input-number
            v-model="requestForm.requestQuantity"
            :min="1"
            :max="material?.quantity"
            placeholder="请输入申请数量"
          />
        </el-form-item>
        <el-form-item label="申请理由" prop="reason">
          <el-input
            v-model="requestForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入申请理由"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="requestDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRequest" :loading="requesting">
            确认申请
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 捐赠对话框 -->
    <el-dialog
      v-model="donateDialogVisible"
      title="捐赠物资"
      width="500px"
    >
      <el-form
        ref="donateFormRef"
        :model="donateForm"
        :rules="donateRules"
        label-width="100px"
      >
        <el-form-item label="捐赠数量" prop="donationNumber">
          <el-input-number
            v-model="donateForm.donationNumber"
            :min="1"
            placeholder="请输入捐赠数量"
          />
        </el-form-item>
        <el-form-item label="捐赠说明" prop="description">
          <el-input
            v-model="donateForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入捐赠说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="donateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitDonate" :loading="donating">
            确认捐赠
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { faker } from '@faker-js/faker'
import {donateMaterial, getMaterialDetail, getMaterialRequests, requestMaterial} from "@/api/material.js";
import {getUserInfo} from "@/utils/auth.js";

const route = useRoute()

// 物资详情
const material = ref(null)

// 申请记录
const requestHistory = ref([])

// 申请相关
const requestDialogVisible = ref(false)
const requestFormRef = ref(null)
const requesting = ref(false)
const requestForm = reactive({
  requestQuantity: 1,
  reason: '',
  materialId: route.params.id,
  userId: getUserInfo().userId
})

// 捐赠相关
const donateDialogVisible = ref(false)
const donateFormRef = ref(null)
const donating = ref(false)
const donateForm = reactive({
  donationNumber: 1,
  description: '',
  materialId: route.params.id,
  userId: getUserInfo().userId
})

const requestRules = {
  requestQuantity: [
    { required: true, message: '请输入申请数量', trigger: 'blur' }
  ],
  reason: [
    { required: true, message: '请输入申请理由', trigger: 'blur' },
    { min: 10, message: '申请理由不能少于10个字符', trigger: 'blur' }
  ]
}

const donateRules = {
  donationNumber: [
    { required: true, message: '请输入捐赠数量', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入捐赠说明', trigger: 'blur' },
    { min: 10, message: '捐赠说明不能少于10个字符', trigger: 'blur' }
  ]
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'warning',  // 待审核
    1: 'success',  // 已批准
    2: 'danger'    // 已拒绝
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待审核',
    1: '已批准',
    2: '已拒绝'
  }
  return texts[status] || '未知'
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

// 加载物资详情
const loadMaterial = async () => {
  const materialId = route.params.id
  const data = await getMaterialDetail(materialId);

  material.value = data.data
}

// 加载申请记录
const loadRequestHistory = async () => {
  const data = await getMaterialRequests({
    materialId: route.params.id,
    page: 1,
    size: 100
  });
  requestHistory.value = data.data.records
}

// 申请相关方法
const handleRequest = () => {
  requestForm.requestQuantity = 1
  requestForm.reason = ''
  requestDialogVisible.value = true
}

const submitRequest = async () => {
  if (!requestFormRef.value) return

  await requestFormRef.value.validate(async (valid) => {
    if (valid) {
      requesting.value = true
      try {
        // TODO: 调用申请API
        await requestMaterial(requestForm)
        ElMessage.success('申请已提交')
        requestDialogVisible.value = false
        await loadMaterial()
        loadRequestHistory()
      } catch (error) {
        console.error('申请失败:', error)
      } finally {
        requesting.value = false
      }
    }
  })
}

// 捐赠相关方法
const handleDonate = () => {
  donateForm.donationNumber = 1
  donateForm.description = ''
  donateDialogVisible.value = true
}

const submitDonate = async () => {
  if (!donateFormRef.value) return

  await donateFormRef.value.validate(async (valid) => {
    if (valid) {
      donating.value = true
      try {
        // TODO: 调用捐赠API
        await donateMaterial(donateForm)
        ElMessage.success('捐赠已提交')
        donateDialogVisible.value = false
        await loadMaterial()
      } catch (error) {
        console.error('捐赠失败:', error)
      } finally {
        donating.value = false
      }
    }
  })
}

onMounted(() => {
  loadMaterial()
  loadRequestHistory()
})
</script>

<style scoped>
.material-detail-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.material-content {
  margin-bottom: 30px;
}

.material-content h2 {
  margin: 0 0 15px 0;
  color: #303133;
}

.meta {
  color: #909399;
  font-size: 14px;
  margin-bottom: 20px;
}

.meta span {
  margin-right: 15px;
}

.description,
.requirements {
  margin-bottom: 20px;
}

.description h3,
.requirements h3 {
  margin: 0 0 10px 0;
  color: #303133;
}

.description p,
.requirements p {
  color: #606266;
  line-height: 1.8;
  margin: 0;
}

.actions {
  margin-top: 20px;
  text-align: center;
}

.donation-history {
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

.donation-history h3 {
  margin: 0 0 20px 0;
  color: #303133;
}
</style>
